import React, { useState } from 'react';
import { Card, Table, Button, Input, Select, Tag, Modal, Form, DatePicker, InputNumber, message } from 'antd';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, FilterOutlined, ReloadOutlined } from '@ant-design/icons';
import { useSelector } from 'react-redux';

const { Option } = Select;
const { RangePicker } = DatePicker;

const ThresholdPromotionManagement = () => {
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState('create'); // 'create' or 'edit'
  const [selectedPromotion, setSelectedPromotion] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const { userInfo } = useSelector((state) => state.auth);

  // 模拟的满减活动数据
  const [promotions, setPromotions] = useState([
    {
      id: '1',
      name: '全场满199减50',
      threshold: 199,
      discount: 50,
      startDate: '2024-01-01',
      endDate: '2024-01-31',
      usageCount: 345,
      maxUsageCount: 1000,
      status: 'active',
      applicableTo: 'all',
      createdBy: 'admin',
    },
    {
      id: '2',
      name: '满399减100',
      threshold: 399,
      discount: 100,
      startDate: '2024-01-10',
      endDate: '2024-02-10',
      usageCount: 234,
      maxUsageCount: 800,
      status: 'active',
      applicableTo: 'all',
      createdBy: 'admin',
    },
    {
      id: '3',
      name: '会员专享满599减150',
      threshold: 599,
      discount: 150,
      startDate: '2024-02-01',
      endDate: '2024-02-28',
      usageCount: 0,
      maxUsageCount: 500,
      status: 'upcoming',
      applicableTo: 'members',
      createdBy: 'admin',
    },
    {
      id: '4',
      name: '限时闪购满99减30',
      threshold: 99,
      discount: 30,
      startDate: '2023-12-25',
      endDate: '2023-12-26',
      usageCount: 456,
      maxUsageCount: 600,
      status: 'expired',
      applicableTo: 'all',
      createdBy: 'admin',
    },
  ]);

  // 表格列定义
  const columns = [
    {
      title: '活动名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a href="#">{text}</a>,
    },
    {
      title: '满减规则',
      key: 'rule',
      render: (record) => `满¥${record.threshold}减¥${record.discount}`,
    },
    {
      title: '有效期',
      key: 'period',
      render: (record) => `${record.startDate} - ${record.endDate}`,
    },
    {
      title: '使用情况',
      key: 'usage',
      render: (record) => `${record.usageCount}/${record.maxUsageCount}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        let color = '';
        let text = '';
        switch (status) {
          case 'active':
            color = 'green';
            text = '活跃';
            break;
          case 'upcoming':
            color = 'orange';
            text = '即将开始';
            break;
          case 'expired':
            color = 'default';
            text = '已过期';
            break;
          default:
            color = 'default';
            text = '未知';
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          {record.status !== 'expired' && (
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
              style={{ marginRight: 8 }}
            >
              编辑
            </Button>
          )}
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </>
      ),
      width: 120,
    },
  ];

  // 过滤满减活动数据
  const filteredPromotions = promotions.filter((promotion) => {
    const matchesSearch = promotion.name.toLowerCase().includes(searchText.toLowerCase());
    const matchesStatus = statusFilter === 'all' || promotion.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  // 打开创建模态框
  const showCreateModal = () => {
    form.resetFields();
    setModalType('create');
    setIsModalVisible(true);
  };

  // 打开编辑模态框
  const handleEdit = (promotion) => {
    setSelectedPromotion(promotion);
    setModalType('edit');
    form.setFieldsValue({
      ...promotion,
      dateRange: [
        new Date(promotion.startDate),
        new Date(promotion.endDate),
      ],
    });
    setIsModalVisible(true);
  };

  // 删除满减活动
  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个满减活动吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setPromotions(promotions.filter((promotion) => promotion.id !== id));
        message.success('满减活动已删除');
      },
    });
  };

  // 提交表单
  const handleSubmit = (values) => {
    if (modalType === 'create') {
      // 创建新满减活动
      const newPromotion = {
        id: Date.now().toString(),
        ...values,
        startDate: values.dateRange[0].format('YYYY-MM-DD'),
        endDate: values.dateRange[1].format('YYYY-MM-DD'),
        usageCount: 0,
        status: 'active',
        createdBy: userInfo?.username,
      };
      setPromotions([newPromotion, ...promotions]);
      message.success('满减活动创建成功');
    } else {
      // 编辑满减活动
      const updatedPromotions = promotions.map((promotion) =>
        promotion.id === selectedPromotion.id
          ? {
              ...promotion,
              ...values,
              startDate: values.dateRange[0].format('YYYY-MM-DD'),
              endDate: values.dateRange[1].format('YYYY-MM-DD'),
            }
          : promotion
      );
      setPromotions(updatedPromotions);
      message.success('满减活动更新成功');
    }
    setIsModalVisible(false);
  };

  // 刷新数据
  const handleRefresh = () => {
    // 这里应该调用API刷新数据，这里简化处理
    message.success('数据已刷新');
  };

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h2>满减活动管理</h2>
        <p style={{ color: '#8c8c8c' }}>管理和创建系统中的满减活动</p>
      </div>

      <Card
        bordered={false}
        style={{ borderRadius: 8, marginBottom: 24 }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <div style={{ display: 'flex', gap: 16 }}>
            <div style={{ width: 200 }}>
              <Input
                placeholder="搜索满减活动名称"
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                style={{ borderRadius: 4 }}
              />
            </div>
            <Select
              placeholder="选择状态"
              value={statusFilter}
              onChange={setStatusFilter}
              style={{ width: 120 }}
              prefix={<FilterOutlined />}
            >
              <Option value="all">全部</Option>
              <Option value="active">活跃</Option>
              <Option value="upcoming">即将开始</Option>
              <Option value="expired">已过期</Option>
            </Select>
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
            >
              刷新
            </Button>
          </div>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={showCreateModal}
          >
            创建满减活动
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={filteredPromotions}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          rowKey="id"
        />
      </Card>

      {/* 创建/编辑满减活动模态框 */}
      <Modal
        title={modalType === 'create' ? '创建满减活动' : '编辑满减活动'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          style={{ maxHeight: '60vh', overflowY: 'auto' }}
        >
          <Form.Item
            name="name"
            label="活动名称"
            rules={[{ required: true, message: '请输入活动名称' }]}
          >
            <Input placeholder="请输入活动名称" />
          </Form.Item>

          <Form.Item
            name="threshold"
            label="满额金额"
            rules={[{ required: true, message: '请输入满额金额' }]}
          >
            <InputNumber
              min={0}
              style={{ width: '100%' }}
              addonBefore="¥"
            />
          </Form.Item>

          <Form.Item
            name="discount"
            label="优惠金额"
            rules={[{ required: true, message: '请输入优惠金额' }]}
          >
            <InputNumber
              min={0}
              style={{ width: '100%' }}
              addonBefore="¥"
            />
          </Form.Item>

          <Form.Item
            name="maxUsageCount"
            label="最大使用次数"
            rules={[{ required: true, message: '请输入最大使用次数' }]}
          >
            <InputNumber
              min={1}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="dateRange"
            label="有效期"
            rules={[{ required: true, message: '请选择有效期' }]}
          >
            <RangePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="applicableTo"
            label="适用对象"
            rules={[{ required: true, message: '请选择适用对象' }]}
          >
            <Select placeholder="请选择适用对象">
              <Option value="all">所有用户</Option>
              <Option value="new_users">新用户</Option>
              <Option value="members">会员用户</Option>
              <Option value="vip">VIP用户</Option>
            </Select>
          </Form.Item>

          <Form.Item style={{ textAlign: 'right' }}>
            <Button style={{ marginRight: 8 }} onClick={() => setIsModalVisible(false)}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              {modalType === 'create' ? '创建' : '保存'}
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ThresholdPromotionManagement;